package kordegi.forumsystem.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import kordegi.forumsystem.common.lang.Result;
import kordegi.forumsystem.entity.Article;
import kordegi.forumsystem.entity.PageRequest;
import kordegi.forumsystem.entity.PageResult;
import kordegi.forumsystem.mapper.ArticleMapper;
import kordegi.forumsystem.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author kordegi
 * @date 2022.05.01 17:01
 * @Description
 */

@Service
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    ArticleMapper articleMapper;

    @Override
    public Article getById(Long id) {
        return articleMapper.selectArticle(id);
    }

    @Override
    public Result findByPager(PageRequest pageRequest) {
        if (getInfo(pageRequest) != null) {
            PageInfo<Article> pageInfo = getInfo(pageRequest);
            Map<String, Object> map = new HashMap<>();
            map.put("pageNum", pageInfo.getPageNum());
            map.put("pageSize", pageInfo.getPageSize());
            map.put("totalSize", pageInfo.getTotal());
            map.put("totalPages", pageInfo.getPages());
            map.put("articles", pageInfo.getList());

            return Result.succ(map);
        } else {
            return Result.fail("分页失败");
        }
    }

    private PageInfo<Article> getInfo (PageRequest pageRequest) {
        int pageNum = pageRequest.getPage();
        int pageSize = pageRequest.getSize();
        PageHelper.startPage(pageNum, pageSize);
        List<Article> articleList = articleMapper.getPageInfo();
        return new PageInfo<>(articleList);
    }

    @Override
    public int saveOrUpdate(Article article) {
        return articleMapper.saveOrUpdate(article);
    }
}
